package Servlets;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import DAL.JDBC.DBConn;
import DAL.JDBC.GameImageJDBC;
import DAL.JDBC.GameJDBC;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;


public class AddGame extends HttpServlet {
	private static final long serialVersionUID = 1L;
	final static String IMAGE_RESOURCE_PATH = "/uploads/";
	private GameJDBC gameJDBC;
	private GameImageJDBC gameImageJDBC;
	
    public AddGame() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void init() throws ServletException
    {
    	gameJDBC = new GameJDBC(DBConn.getConnection());
    	gameImageJDBC = new GameImageJDBC(DBConn.getConnection());
    }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		JSONObject result = new JSONObject();
		
		String ajaxUpdateResult = "";
		String directoryPath = getServletContext().getRealPath(IMAGE_RESOURCE_PATH);
		File directory = new File(directoryPath);

		
		if(!directory.exists()) {
		    directory.mkdirs();
		}
		
		String name = "";
		String description = "";
		String trailer = "";
		int consoleId = 0;
		int genreId = 0;
		int quantity = 0;
		int price = 0;
		int insertedId = 0;
		List<String> images = new ArrayList<String>();
		
		try {
			List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

			for (FileItem item : items) {
				if (item.isFormField()) {
					//ajaxUpdateResult += "Field " + item.getFieldName() + " with value: " + item.getString() + " is successfully read\n\r";
					String itemName = item.getFieldName();
					switch (itemName) {
					case "name":
						name = item.getString();
						break;
					case "consoleID":
						consoleId = Integer.parseInt(item.getString());
						break;
					case "genreId":
						genreId = Integer.parseInt(item.getString());
						break;
					case "description":
						description = item.getString();
						break;
					case "trailer":
						trailer = item.getString();
						break;
					case "quantity":
						quantity = Integer.parseInt(item.getString());
						break;
					case "price":
						price = Integer.parseInt(item.getString());
						break;
					default:
						break;
					}
				} else {
					String fileName = directoryPath + File.separator + item.getName();
					InputStream content = item.getInputStream();

					//response.setContentType("text/plain");
					//response.setCharacterEncoding("UTF-8");

					File saveTo = new File(fileName);
					item.write(saveTo);
					images.add(item.getName());

					// Do whatever with the content InputStream.
					System.out.println(Streams.asString(content));

					ajaxUpdateResult += "File " + fileName;
					
					
				}
			}
		}
		catch 
		
		(FileUploadException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try
		{
			insertedId = gameJDBC.insert(name, description, trailer, consoleId, genreId, quantity, price);
			for (String image : images) {
				gameImageJDBC.insert(insertedId, image);
			}
			result.put("result", true);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			try {
				result.put("result", false);
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

		try {
			result.put("images", ajaxUpdateResult);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		PrintWriter pw = response.getWriter();
		pw.write(result.toString());
		
	}
}
